//
// Created by Zsir on 2025/8/22.
//

#include "EventLoopThreadPool.h"
#include "EventLoopThread.h"
#include <iostream>

EventLoopThreadPool::EventLoopThreadPool(EventLoop* baseLoop, int numThreads)
    : baseLoop_(baseLoop),
      numThreads_(numThreads),
      next_(0) {}

EventLoopThreadPool::~EventLoopThreadPool() {
    std::cout << "销毁 EventLoopThreadPool" << std::endl;
}

/*
 * 创建线程池，但还没启动线程任务
 * 启动线程任务
 * 保存线程和线程所对应的 EventLoop
 */

void EventLoopThreadPool::start() {
    for (int i = 0; i < numThreads_; ++i) {
        auto thread = std::make_unique<EventLoopThread>();
        EventLoop* loop = thread->startLoop();
        threads_.push_back(std::move(thread));
        loops_.push_back(loop);
    }
}

EventLoop* EventLoopThreadPool::getNextLoop() {
    EventLoop* loop = baseLoop_;
    if (!loops_.empty()) {
        loop = loops_[next_];
        next_ = (next_ + 1) % loops_.size();
    }
    return loop;
}